import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RedisRepository {
    private final JedisPool jedisPool;
    private static final String CAR_PATH_FORMAT = "car:%s:path";
    private static final String CAR_POSITION_FORMAT = "car:%s:position";
    public RedisRepository(String host, int port) {
        this.jedisPool = new JedisPool(host, port);
    }

    public MapData getMapData() {
        try (Jedis jedis = jedisPool.getResource()) {
            Pipeline p = jedis.pipelined();
            Response<String> widthResp = p.get("mapwidth");
            Response<String> heightResp = p.get("mapheight");
            //到时候特判一下小车的坐标
            Response<String> obstacleResp = p.get("map:obstacle");
            Response<String> lightResp = p.get("map:light");
            Response<String> carcount = p.get("carcount");
            p.sync();

            int width = Integer.parseInt(widthResp.get());
            int height = Integer.parseInt(heightResp.get());

            int count = 0;
            HashMap<String, Boolean> CarMap = new HashMap<>();
            HashMap<String, Integer>CarId=new HashMap<>();
            if (carcount != null && carcount.get() != null) {
                count = Integer.parseInt(carcount.get());
                for (int i = 1; i <= count; i++) {
                    String pos = getCarPosition(String.valueOf(i));
                    if (pos != null) {
                        CarMap.put(pos, true);
                        CarId.put(pos,i);
                    }
                }
            }

            String obstaclesStr = obstacleResp.get();
            String lightsStr = lightResp.get();

            return new MapData(width, height, obstaclesStr, lightsStr, count, CarMap,CarId);
        } catch (Exception e) {
            System.err.println("Redis读取失败，使用默认地图大小 10x10");
            return new MapData(10, 10, "", "", 0, null,null);
        }
    }

    public String getCarPosition(String carId) {
        try (Jedis jedis = jedisPool.getResource()) {
            Map<String, String> pos = jedis.hgetAll("car:" + carId + ":position");
            if (pos.isEmpty()) {
                return null;
            }
            String x = pos.get("x");
            String y = pos.get("y");
            return x + " " + y;
        } catch (Exception e) {
            return null;
        }
    }
    //获取zadd这个列表，按照score从小到大进行排序了
    public List<Tuple> getcarpath(String carId) {
        String key = String.format(CAR_PATH_FORMAT, carId);
        System.out.println("🔍 正在查询 Redis 路径 key: " + key);

        try (Jedis jedis = jedisPool.getResource()) {
            List<Tuple> result = jedis.zrangeWithScores(key, 0, -1);
            if (result == null || result.isEmpty()) {
                System.out.println("⚠️ Redis 返回空结果，请确认 key 是否有数据");
            } else {
                System.out.println("✅ 成功获取路径点数量: " + result.size());
            }
            return result;
        } catch (Exception e) {
            System.err.println("❌ 查询 Redis 路径失败: " + key + ", 错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    public static class MapData {
        public final int width;
        public final int height;
        public final String obstaclesStr;
        public final String lightsStr;
        public final int count;
        public final HashMap<String, Boolean> CarMap;
        public final HashMap<String, Integer> CarId; // 修改为Integer

        public MapData(int width, int height, String obstaclesStr, String lightsStr, int count, HashMap<String, Boolean> car,HashMap<String,Integer>carid) {
            this.width = width;
            this.height = height;
            this.obstaclesStr = obstaclesStr;
            this.lightsStr = lightsStr;
            this.count = count;
            this.CarMap = car;
            this.CarId=carid;
        }
    }
    //获取地图宽度
    public int getMapWidth() {
        try (Jedis jedis = jedisPool.getResource()) {
            String width = jedis.get("mapwidth");
            return width == null ? 0 : Integer.parseInt(width);
        } catch (Exception e) {
            return 0;
        }
    }

    // 获取地图高度
    public int getMapHeight() {

        try (Jedis jedis = jedisPool.getResource()) {
            String width = jedis.get("mapheight");
            return width == null ? 0 : Integer.parseInt(width);
        } catch (Exception e) {
            return 0;
        }
    }

    //获取小车数量
    public int getCarcount()
    {
        try (Jedis jedis = jedisPool.getResource()) {
            String width = jedis.get("carcount");
            return width == null ? 0 : Integer.parseInt(width);
        } catch (Exception e) {
            return 0;
        }
    }
    //获取静态地图
    public String getstaticmap()
    {
        try (Jedis jedis = jedisPool.getResource()) {
            String mapobstacle = jedis.get("map:obstacle");
            if (mapobstacle == null) {
                System.err.println("❌ 障碍物数据为空");
                return null;
            }
            int count = getCarcount();
            int width = getMapWidth();
            // 使用 StringBuilder 支持修改
            StringBuilder obstacleBuilder = new StringBuilder(mapobstacle);

            for (int i = 1; i <= count; i++) {
                Position car = loadCarPosition(String.valueOf(i));
                if (car != null) {
                    int index = car.y * width + car.x;
                    if (index >= 0 && index < obstacleBuilder.length()) {
                        obstacleBuilder.setCharAt(index, '0');  // 将小车位置置为 0
                    } else {
                        System.err.println("⚠️ 小车坐标超出障碍物矩阵范围: " + car);
                    }
                }
            }
            return obstacleBuilder.toString();  // 返回处理后的障碍物字符串
        } catch (Exception e) {
            return null;
        }
    }
    //获取坐标
    // 坐标结构体
    private static class Position {
        int x, y;

        Position(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return x + " " + y;
        }
    }
    //加载小车位置
    private Position loadCarPosition(String carId) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = String.format(CAR_POSITION_FORMAT, carId);
            String xStr = jedis.hget(key, "x");
            String yStr = jedis.hget(key, "y");

            if (xStr == null || yStr == null) return null;

            try {
                int x = Integer.parseInt(xStr);
                int y = Integer.parseInt(yStr);
                return new Position(x, y);
            } catch (NumberFormatException e) {
                System.out.println("小车位置数据异常");
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
}
